package database.service;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;

import database.auxiliary.LogGenerator;

import po.UserPO;

public class UserDataServiceSerializableImpl implements UserDataService {

	private ArrayList<UserPO> userList;

	public UserDataServiceSerializableImpl() {
		userList = new ArrayList<UserPO>();
	}

	@Override
	public void load() {
		try {
			File file = new File("data/user.ser");
			if (!file.exists()) {
				file.createNewFile();
			}
			ObjectInputStream oiStream = new ObjectInputStream(
					new FileInputStream(file));
			UserPO userPO;
			while ((userPO = (UserPO) oiStream.readObject()) != null) {
				userList.add(userPO);
			}
			LogGenerator.log("User data load succeed, length: " + userList.size());
		} catch (EOFException e) {
			save();
			load();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void save() {
		try {
			FileOutputStream fos = new FileOutputStream("data/user.ser");
			ObjectOutputStream outputStream = new ObjectOutputStream(fos);
			for (int i = 0; i < userList.size(); i++) {
				outputStream.writeObject(userList.get(i));
			}
			outputStream.writeObject(null);
			outputStream.close();
			LogGenerator.log("User data save succeed");
		} catch (FileNotFoundException e) {
			System.out.println("File found failed!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public int insert(UserPO user) {
		user.setId(userList.size() + 1);
		userList.add(user);
		LogGenerator.log("User insert: " + user);
		return userList.size();
	}

	@Override
	public void delete(UserPO user){
		for(int i=0;i<userList.size();i++){
			if(user.getId()==userList.get(i).getId()){
				userList.get(i).setId(-user.getId());
				LogGenerator.log("User delete: " + user);
				break;
			}
		}
	}

	@Override
	public void update(UserPO user) {
		for (int i = 0; i < userList.size(); i++) {
			if (user.getId() == userList.get(i).getId()) {
				userList.set(i, user);
				LogGenerator.log("User update: " + user);
			}
		}
	}

	@Override
	public UserPO find(int id) {
		for (int i = 0; i < userList.size(); i++) {
			if (id == userList.get(i).getId()) {
				LogGenerator.log("User find: " + userList.get(i));
				return new UserPO(userList.get(i));
			}
		}
		return null;
	}

	@Override
	public Iterator<UserPO> getIterator() {
		LogGenerator.log("User return itr, length = " + userList.size());
		return userList.iterator();
	}

}
